component output="false" extends="AbsService" accessors="true" {

	// Factories
	property name="UserFactory" type="it.millemultimedia.easyBlog.factory.UserFactory";
	// Delegate
	property name="UserDelegate" type="it.millemultimedia.easyBlog.delegate.UserDelegate";
	// Util
	property name="Security" type="it.millemultimedia.util.Security";
	
	
	public it.millemultimedia.easyBlog.service.UserService function init(){
		
		return this;
	}
	
	public it.millemultimedia.easyBlog.validator.UserValidator function getValidator(){
		
		return getUserFactory().createValidator();
	}
	
	public it.millemultimedia.easyBlog.model.User function new(){
	
		var user = getUserFactory().createInstance();
		
		return user;
	}
	
	public it.millemultimedia.easyBlog.model.User function getUser( required Any User ){
	
		var userObj = getUserFactory().get( arguments.User );
	
		userObj.setUsername( getSecurity().decryptString( userObj.getUsername() ) );
		userObj.setPassword( getSecurity().decryptString( userObj.getPassword() ) );
		
		return userObj;
	}
	
	public it.millemultimedia.easyBlog.model.User[] function getUsers( required Any User ){
		
		return getUserFactory().createList( arguments.User );
	}
	
	public boolean function userExists( required Any User ){
		var result = getUserFactory().createList( arguments.User );
		
		return arrayLen( result ) gt 0;
	}
	
	public void function saveUser( required Any User ){
	
		transaction{
		
			try{
			
				arguments.User.setUsername( getSecurity().encryptString( arguments.User.getUsername() ) );
				arguments.User.setPassword( getSecurity().encryptString( arguments.User.getPassword() ) );
			
				if( arguments.User.getIdUser() eq 0 ){
				
					this.createUser( arguments.User );
				
				}else if( arguments.User.getIdUser() gt 0 ){
				
					this.updateUser( arguments.User );
				
				}else{
				
					throw( message="User id property have undefined value." );
				
				}
			
			}catch( except Any ){
			
				transaction action="rollback";
				
				throw( except.message );
			
			}
		
		}
		
	}
	
	public void function createUser( required Any User ){
	
		transaction{
		
			try{
			
				getUserDelegate().create( arguments.User );
			
			}catch( except Any ){
			
				transaction action="rollback";
				
				throw( except.message );
			
			}
		
		}
		
	}
	
	public void function updateUser( required Any User ){
	
		transaction{
		
			try{
			
				getUserDelegate().update( arguments.User );
			
			}catch( except Any ){
			
				transaction action="rollback";
				
				throw( except.message );
			
			}
		
		}
		
	}
	
	public void function deleteUser( required Any User ){
	
		transaction{
		
			try{
			
				getUserDelegate().delete( arguments.User );
				
			
			}catch( except Any ){
			
				transaction action="rollback";
				
				throw( except.message );
							
			}
			
		}
		
	}
	
}
